package com.example.crawler.lianjia.processor;


import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Strings;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;

import static com.example.crawler.lianjia.util.TimeUtil.getFirstTimeByToday;
import static com.example.crawler.lianjia.util.TimeUtil.getTimestamp;


@Slf4j
public class LianjiaHouseProcessor implements PageProcessor {


    @Override
    public Site getSite() {
        return Site.me().setRetryTimes(3).setSleepTime(100);
    }

    @Override
    public void process(Page page) {

        //判断标志，判断下一页是否需要加入爬虫处理
        boolean isNextAddProcessor = true;
        //当天开始时
        Long nowStartTime = getFirstTimeByToday();

        List<Selectable> temps = page.getHtml().xpath("//div[@class='resblock-list-container clearfix']/ul[2]/li").nodes();
        log.info("文章 list={}", temps.toString());
        for (Selectable selectable : temps) {
            String timeString = selectable.xpath("//*[@class='f12 blue_lighten']/text(1)").get();
            //解析时间成时间戳
            Long time = getTimestamp(timeString.substring(2));
            if (time < nowStartTime) {
                isNextAddProcessor = false;
                break;
            }
            //标题
            String title = selectable.xpath("//p/a/img/@alt").get();

            //网页详情路径
            String contentUrl = selectable.xpath("//p/a/@href").get();

            //封面
            String coverUrl = selectable.xpath("//p/a/img/@src").get();

            //简介
            String introduction = selectable.xpath("//div/p[2]/text(0)").get();

        }

        if (isNextAddProcessor) {
            //当前页是今天的，继续获取下一页链接
            List<String> pageList = page.getHtml().xpath("//div[1]/div[@class='listpage mt30 page_comm']").links().all();
            String url = pageList.get(pageList.size() - 1);
            if (!Strings.isNullOrEmpty(url)) {
                //从页面发现后续的url地址来抓取
                page.addTargetRequest(url);
            }
            log.info("分页路径 pageUrls={}", pageList);
        }

    }

    public static void main(String[] args) {
        Spider.create(new LianjiaHouseProcessor()).addUrl("https://xa.fang.lianjia.com/loupan/").thread(5).run();
    }


}
